<template>
  <div
    v-loading="loading"
    class="monthPlanAdd"
  >
    <div class="pub-detail-title-btn">
      <template v-if="state !== 3">
        <a-button
          type="primary"
          icon="plus"
          :loading="loadingData.add"
          @click="addRow('add')"
        >
          添加行
        </a-button>
        <a-button
          type="danger"
          icon="delete"
          @click="handleDel"
        >
          删除行
        </a-button>
        <!-- <a-button>
                    导出模板
                </a-button>
                <a-button>
                    导入
                </a-button> -->
      </template>
      <excel
        ref="exportSelect"
        file-name="机械设备需用总计划"
        is-click-generate="false"
      >
        <a-button
          slot="excelBtn"
          icon="download"
          type="primary"
          :disabled="selectedRowKeys.length == 0"
          @click="exportSelect"
        >
          导出选中
        </a-button>
      </excel>
      <excel
        ref="exportAll"
        file-name="机械设备需用总计划"
        is-click-generate="false"
      >
        <a-button
          slot="excelBtn"
          icon="download"
          type="primary"
          @click="exportAll"
        >
          导出全部
        </a-button>
      </excel>
      <a-button
        v-if="state !== 3"
        icon="download"
        type="primary"
        :loading="loadingData.download"
        @click="addRow('download')"
      >
        标准模板下载
      </a-button>
      <!-- 导入 -->
      <ExcelImportButton
        v-if="state !== 3"
        ref="excelImportButton"
        v-btnPermission="'lu_0014_imp_05'"
        icon="import"
        class="ml12"
        @handleSubmit="handleSubmit"
      />
    </div>
    <a-table
      ref="table"
      :pagination="false"
      :columns="columns"
      :data-source="data"
      bordered
      class="bgFFF"
      :scroll="{ x: 1300 }"
      row-key="id"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >
      <span
        slot="index"
        slot-scope="text, record, index"
      >{{ index + 1 }}</span>
      <template
        v-for="col in [
          'materialName',
          'materialCode',
          'materialModel',
          'materialUnit',
          'planNum',
          'planIntoDate',
          'planOutDate',
          'remark'
        ]"
        :slot="col"
        slot-scope="text, record"
      >
        <div
          :key="col"
          class="form-item"
        >
          <template v-if="state !== 3">
            <a-date-picker
              v-if="col === 'planIntoDate'"
              v-model="record.planIntoDate"
              value-format="YYYY-MM-DD"
              type="date"
              @change="(e) => handleChange(record.planIntoDate, record.id, col)"
            />
            <a-date-picker
              v-else-if="col === 'planOutDate'"
              v-model="record.planOutDate"
              value-format="YYYY-MM-DD"
              type="date"
              @change="(e) => handleChange(record.planOutDate, record.id, col)"
            />
            <BaseInput
              v-else-if="
                col === 'remark' ||
                  col === 'materialName' ||
                  col === 'materialCode' ||
                  col === 'materialModel' ||
                  col === 'materialUnit'
              "
              v-model="record[col]"
              :class="col === 'remark' ? 'remark' : ''"
              :show-tip-length="5"
              style="margin: -5px 0"
              :disabled="
                col === 'materialName' ||
                  col === 'materialCode' ||
                  col === 'materialModel' ||
                  col === 'materialUnit'
              "
              @blur="save(record)"
            />
            <BaseInputNumber
              v-else-if="col === 'planNum'"
              v-model="record[col]"
              :precision="3"
              style="margin: -5px 0"
              @blur="save(record)"
            />
            <BaseInputNumber
              v-else
              v-model="record[col]"
              :precision="2"
              style="margin: -5px 0"
              @blur="save(record)"
            />
          </template>
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
      <!-- <template slot="operation" slot-scope="text, record">
                <div class="editable-row-operations">
                    <span v-if="record.editable && state !== 3">
                        <a @click="() => save(record.id)">保存</a>
                        <a @click="cancel(record.id)">取消</a>
                    </span>
                    <span v-else>
                        <a :disabled="editingKey !== ''" @click="() => edit(record.id)">编辑</a>
                    </span>
                </div>
            </template> -->
    </a-table>
    <pagination
      v-model="pageNo"
      :total="totalSize"
      :page-size.sync="pageSize"
      @change="handlePageChange"
      @showSizeChange="showSizeChange"
    />
    <materialListAndDir
      ref="detailDialog"
      @createList="createList"
    />
  </div>
</template>
<script>
import {
    equipmentList,
    equipmentAdd,
    equipmentEdit,
    equipmentDel,
    downloadExcel
} from '@/api/material/materialMasterPlan/materialPlan'
import { equimentColumns } from './insideModel'
import { handleDate } from '@/utils/excelDateUtil'
import materialListAndDir from '@/components/materialListAndDir/materialListAndDir'
const data = []
export default {
    name: 'RebarPlan',
    props: {
        state: {
            type: Number
        },
        id: {
            type: String
        }
    },
    components: {
        materialListAndDir
    },
    data() {
        this.cacheData = data.map((item) => ({ ...item }))
        return {
            loading: false,
            selectedRows: [],
            pageNo: 1,
            pageSize: 10,
            totalSize: 0,
            selectedRowKeys: [],
            columns: equimentColumns,
            editingKey: '',
            data: [],
            optionArr: [],
            selectedId: [],
            selectVal: null,
            rules: {
                planNum: [{ rule: 'required', message: '计划数量不能为空' }],
                planIntoDate: { rule: 'required', message: '计划进场日期不能为空' },
                planOutDate: { rule: 'required', message: '计划退场日期不能为空' }
            },
            loadingData: {
                add: false,
                download: false
            },
            downloadExcel: downloadExcel,
            importCheck: {
                设备名称: 'materialName',
                物料编码: 'materialCode',
                规格型号: 'materialModel',
                单位: 'materialUnit',
                计划数量: 'planNum',
                计划进场日期: 'planIntoDate',
                计划退场日期: 'planOutDate',
                备注: 'remark'
            } // 导入字段对应
        }
    },
    watch: {},
    mounted: function () {
        if (this.state === 3) {
            this.editingKey = true
        }
        this.list()
        this.initErrMessage(this.rules)
        this.$refs.exportSelect.tableToExcelFile(this.$refs.table)
        this.$refs.exportAll.tableToExcelFile(this.$refs.table)
    },
    methods: {
        exportSelect: function () {
            if (this.selectedRowKeys.length > 0) {
                this.$refs.exportSelect.setDataAndGenerate(this.selectedRows)
            } else {
                this.$message.warning('请选择需要导出的数据')
            }
        },
        exportAll: function () {
            // 参数：查询条件、导出的回调
            if (this.totalSize) {
                this.pageNo = 1
                this.list(this.$refs.exportAll.setDataAndGenerate)
            } else {
                this.$message.warning('没有可导出的数据')
            }
        },

        createList(data) {
            let params = []
            data.forEach((item) => {
                params.push({
                    materialCode: item.code,
                    materialModel: item.specificationModel,
                    materialName: item.name,
                    materialUnit: item.unitId,
                    planIntoDate: null,
                    planNum: null,
                    planOutDate: '',
                    projectId: this.id,
                    remark: '',
                    materialId: item.id
                })
            })

            this.loading = true
            equipmentAdd(params).then((res) => {
                if (res.code === 200) {
                    this.initTable()
                }
            })
        },
        async addRow(type) {
            let temp = []
            if (this.totalSize !== 0) {
                this.loadingData[type] = true
                let res = await equipmentList({
                    pageSize: this.totalSize,
                    pageNo: 1,
                    id: this.id
                })
                this.loadingData[type] = false
                temp = res.data
            }
            if (type === 'add') {
                this.$refs.detailDialog.open(temp)
            } else {
                this.$refs.detailDialog.download(temp, this.downloadExcel, { type: 5 })
            }
        },
        // 删除
        handleDel() {
            this.loading = !!this.selectedId.length
            this.delList2(
                equipmentDel,
                () => {
                     this.pageNo =
                        this.pageNo - 1 < (this.totalSize - this.selectedId.length) / this.pageSize
                            ? this.pageNo
                            : this.pageNo - 1
                    this.list()
                    this.selectedId = []
                    this.selectedRowKeys = []
                    this.selectedRows = []
                    this.editingKey = ''
                    this.loading = false
                },
                { ids: this.selectedId },
                () => {
                    this.loading = false
                }
            )
        },
        initTable() {
            this.pageNo = 1
            this.list()
        },
        list(callback) {
            let _this = this
            this.loading = true
            equipmentList({
                pageSize: callback ? this.totalSize : this.pageSize,
                pageNo: _this.pageNo,
                id: _this.id
            }).then((res) => {
                if (res.code === 200) {
                    if (callback) {
                        if (res.data.length) {
                            callback(res.data)
                        } else {
                            this.$message.warning('没有可导出的数据')
                        }
                        this.loading = false
                        return
                    }
                    _this.data = res.data
                    _this.totalSize = res.totalSize
                    _this.cacheData = res.data.map((item) => ({ ...item }))
                }
                this.loading = false
            })
        },
        handleChange(value, key, column) {
            const newData = [...this.data]
            const target = newData.filter((item) => key === item.id)[0]
            if (target) {
                target[column] = value
                // if (this.rules[column]) {
                //     this.customValidation(value, column)
                // }
                this.save(target)
                this.data = newData
            }
        },
        handlePageChange(pageNo, pageSize) {
            this.pageNo = pageNo
            this.list()
           this.selectedId = []
                    this.selectedRowKeys = []
                    this.selectedRows = []
        },
        showSizeChange(pageNo, pageSize) {
            this.pageSize = pageSize
            this.initTable()
        },
        async save(row) {
            await equipmentEdit(row)
        },

        onSelectChange(selectedRowKeys, selectedRows) {
            this.selectedId = []
            selectedRows.map((i) => {
                this.selectedId.push(i.id)
            })
            this.selectedRowKeys = selectedRowKeys
            this.selectedRows = selectedRows
        },
        /**
         * 导入记录
         */

        handleSubmit(e) {
            let form = []
            console.log(e)
            const date = /^(\d{16}|\d{19})$/
            for (let index in e) {
                form.push({})
                let keys = e[index]
                let listItem = form[index]
                // 校验excel的表头数量
                // if (Object.keys(keys)?.length === 7) {
                // 校验excel的表头字段
                for (let i in this.importCheck) {
                    let item = this.importCheck[i]
                    if (!Object.keys(keys).includes(i) && i == '计划数量') {
                        this.$message.warning(`${i}必填`)
                        return
                    } else {
                        listItem[item] = keys[i]
                        if (item == 'planNum') {
                            if (isNaN(parseInt(listItem[item]))) {
                                this.$message.warning(`${i}必须为数字`)
                                return
                            }
                        } 
                        // else if (item == 'planIntoDate' || item == 'planOutDate') {
                        //     listItem[item] = handleDate(listItem[item], 'yyyy-MM-dd')
                        //     // if (!date.test(listItem[item])) {
                        //     //     this.$message.warning('请输入正确的日期格式:YYYY-MM-DD')
                        //     //     return
                        //     // }
                        // }

                        listItem.projectId = this.id
                    }
                }
                // } else {
                //     this.$message.warning('数据不完整')
                //     return
                // }
            }
            console.log(form)
            this.loading = true
            equipmentAdd(form).then(
                (res) => {
                    if (res.code == 200) {
                        console.log(res)
                        this.$message.success('导入成功')
                        this.initTable()
                    } else {
                        this.loading = false
                    }
                },
                (error) => {
                    console.log(error)
                    const errors = error.data.message.split('/')
                    if (errors.length > 0) {
                        this.$info({
                            title: '提示',
                            width: '650px',
                            content: function () {
                                return errors.map((i, index) => (
                                    <p style="margin-bottom: 10px;">
                                        {index + 1 > 2 ? index - 1 + ':' : ''}
                                        {i}
                                    </p>
                                ))
                            },
                            onOk() {}
                        })
                    }

                    this.loading = false
                }
            )
        }
    }
}
</script>
<style lang="less" scoped>
/deep/ .form-item  {
    .ant-input:not([disabled]),
    .ant-select:not(.ant-select-disabled) .ant-select-selection,
    .ant-calendar-picker-input,
    .ant-input-number-input,
    .ant-cascader-picker {
        border-color: #e4ac0b;
        background-color: #fff9e8;
    }
    .remark {
        .ant-input {
            border-color: inherit;
            background-color: initial;
        }
    }
}
</style>